package com.qzimp.fujiancuo.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.qzimp.fujiancuo.entity.Userinfo;
import com.qzimp.fujiancuo.entity.UserinfoLog;
import com.qzimp.fujiancuo.entity.vo.ResultCode;
import com.qzimp.fujiancuo.entity.vo.UserHaveLogsVo;
import com.qzimp.fujiancuo.exceptions.ApiException;
import com.qzimp.fujiancuo.mapper.UserinfoMapper;
import com.qzimp.fujiancuo.service.UserinfoLogService;
import com.qzimp.fujiancuo.service.UserinfoService;
import com.qzimp.fujiancuo.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *  服务层实现。
 *
 * @author 李欧雯
 * @since 2024-12-20
 */
@Service
public class UserinfoServiceImpl extends ServiceImpl<UserinfoMapper, Userinfo> implements UserinfoService {
    @Autowired
    private  UserinfoMapper userinfoMapper;
    @Autowired
    private UserinfoLogService userinfoLogService;
    @Override
    public Userinfo findUserinfoByLoginName(String loginName) {

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("login_name",loginName);

        return userinfoMapper.selectOneByQuery(queryWrapper);
    }
    //执行登录操作
    @Override
    public Userinfo login(String loginName, String password) {
        //使用QuerWrapper根据用户名和密码查询
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("login_name",loginName);
        queryWrapper.eq("password",password);
        //调用userinfomapper调用select方法查询
        Userinfo userinfo= userinfoMapper.selectOneByQuery(queryWrapper);
        if(userinfo==null){
            throw  new ApiException(ResultCode.USER_LOGIN_NAME_NOT_EXIST);
        }
        //生成token
        //使用JWT令牌并设置令牌时间和密钥
        final  String token= JWT.create()
                .setNotBefore(DateUtil.date())
                .setKey("abcdef".getBytes())
                .sign();
        userinfo.setToken(token);
        //更新token
        int ok= userinfoMapper.update(userinfo);
        if(ok<1){
            if(userinfo==null){
                throw  new ApiException(ResultCode.USER_TOKEN_UPDATE_FAILURE);
            }
        }

        return  userinfo;

    }

    @Override
    public UserHaveLogsVo queryUserHaveLogs(String loginName) {
        //获取管理员信息通过管理员账号
        Userinfo userinfo=this.queryUserinfoByName(loginName);
        if(userinfo==null){
            throw  new ApiException(ResultCode.CUSTOM_ERROR,"用户账户不存在");
        }
        // 通过管理员编号获取日志信息
        List<UserinfoLog> logList= userinfoLogService.queryUserinfoLogs(userinfo.getId());
        //把所有的信息放到包装类AdminHaveLogsVo
        UserHaveLogsVo userHaveLogsVo=new UserHaveLogsVo();

        userHaveLogsVo.setLoginName(loginName);
        userHaveLogsVo.setUserinfoLogList(logList);
        return userHaveLogsVo;
    }

    private Userinfo queryUserinfoByName(String loginName) {
        QueryWrapper queryWrapper=new QueryWrapper();

        queryWrapper.eq("login_name",loginName);

        return userinfoMapper.selectOneByQuery(queryWrapper);
    }
    @Override
    public void updatePasswordById(Integer userId, String newPassword) {
        // 根据用户ID查询用户信息
        Userinfo userinfo = userinfoMapper.selectById(userId);
        // 如果查询结果为空，即用户不存在，抛出异常
        if (userinfo == null) {
            throw new ApiException(ResultCode.NO_DATA_ERROR);
        }
        String salt = userinfo.getSalt();
        String encryptedPassword = StringUtil.MD5(newPassword + salt);
        QueryWrapper updateWrapper = new QueryWrapper();
        updateWrapper.eq("id", userId);
        // 创建一个新的Userinfo对象，用于存储更新后的密码信息
        Userinfo updateInfo = new Userinfo();
        updateInfo.setPassword(encryptedPassword);
        // 调用Mapper的updateByQuery方法，根据条件更新用户密码
        userinfoMapper.updateByQuery(updateInfo, updateWrapper);
    }

    @Override
    public Userinfo findUserinfoByUserId(Integer userId) {
        QueryWrapper queryWrapper=new QueryWrapper();

        queryWrapper.eq("id",userId);

        return userinfoMapper.selectOneByQuery(queryWrapper);
    }


}
